<?php
require_once ("db.inc");
require_once ("math.inc");
require_once ("xajax/xajax_core/xajax.inc.php");

define ("domain","http://путя.рф/");
define ("empty_link_text","Вставьте сюда вашу ссылку...");
$xajax = new xajax();
$xajax->registerFunction("get_short_link");

function get_short_link ($arg){
    // проверить ссылка ли это!!!
    $objResponse = new xajaxResponse();

    if ($arg == empty_link_text) {
        $objResponse->assign("txtshort", "value", "Пусто :(");
    }
    else if (mb_strpos($arg,"путя.рф")) {
        $objResponse->assign("txtshort", "value", "Ну ну ;D");
    }
    else if (preg_match("#^(http|https|ftp)\://#", $arg)) {
        if ( $id = getmysqli_query ("SELECT `simple`.`id` FROM `putya`.`simple` WHERE `simple`.`link` = '".$arg."'")) {
            $short = get76from10($id[0]['id']);
            $objResponse->assign("txtshort", "value", domain.$short);
        }
        else
        {
            if ( $identity = getmysqli_query ("INSERT INTO `putya`.`simple` (`id` ,`link`) VALUES ( NULL , '".$arg."');"))
            {
                $code76 = get76from10($identity);
                $objResponse->assign("txtshort", "value", domain.$code76);
            }
        }
    }
    else
        $objResponse->assign("txtshort", "value", "Ты ввел белиберду ;)");

    return $objResponse;
}


$xajax->processRequest();

$free_url="Что сократить?!";


if (isset($_POST['token'])) {
    $url = "http://loginza.ru/api/authinfo?token=".$_POST['token'];
    $urlcontent = file_get_contents($url) or die("Could not access site: $url");
    $obj = json_decode($urlcontent);

    if (isset($_REQUEST[session_name()])) session_start();
    
    if ($result = getmysqli_query ("SELECT * FROM `logins` WHERE `identity` = '".$obj->{'identity'}."'")) {
        $_SESSION['authorized']   = $result[0][id];
        $_SESSION['identity']     = $result[0][identity];
        $_SESSION['provider']     = $result[0][provider];
        $_SESSION['photo']        = $result[0][photo];
        $_SESSION['first_name']   = $result[0][first_name];
        $_SESSION['last_name']    = $result[0][last_name];
    }
    else {
        $query  = "INSERT INTO `putya`.`logins` ";
        $query .= "(`id`, `mergeid`, `identity`, `provider`, `photo`, `first_name`, `last_name`) ";
        $query .= "VALUES (NULL, NULL, '".$obj->{'identity'}."', '".$obj->{'provider'}."', '".$obj->{'photo'}."', '".$obj->{'name'}->{'first_name'}."', '".$obj->{'name'}->{'last_name'}."');";
        $identity = getmysqli_query ($query);
        $_SESSION['authorized']   = $identity;
        $_SESSION['identity']     = $obj->{'identity'};
        $_SESSION['provider']     = $obj->{'provider'};
        $_SESSION['photo']        = $obj->{'photo'};
        $_SESSION['first_name']   = $obj->{'name'}->{'first_name'};
        $_SESSION['last_name']    = $obj->{'name'}->{'last_name'};
    }

    //print_r ($_SESSION);
    //exit;
}

$uri = substr($_SERVER[REQUEST_URI],1);
//print_r($_SERVER);
if (!isset($_GET['getlink']) && !empty($uri))
//if (!isset($_GET['getlink']) && !empty($uri) && $_SERVER['REMOTE_ADDR'] == '213.170.92.14')
{
    // поиск по базе
    $uri = urldecode($uri);
    if (preg_match("/^[а-яА-Я0-9]{1,10}+$/u", $uri)) {

        $code10 = get10from76($uri);
        if ( $result = getmysqli_query ("SELECT `link` FROM `simple` WHERE `id` = '".$code10."'")) {
            getmysqli_query ("INSERT INTO `putya`.`statistic` (`id` ,`date`,`linkid`,`comments`) VALUES ( NULL , CURDATE(),'".$code10."','".$_SERVER['REMOTE_ADDR']."');");
            $result = $result[0]['link'];
            header ("Location: ".$result."");
        }
        else
        {
            $free_url = domain.$uri;
        }

    }
}

?>
<!DOCTYPE html>
<html lang="ru">
<head>

    <meta charset="utf-8" />

    <!-- Always force latest IE rendering engine (even in intranet)
         & Chrome Frame -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

    <title>ПУТЯ.РФ - Сокращатель ссылок по-русски</title>

    <meta name="description" content="путя.рф - сокращаем ссылки">
    <meta name="keywords" content="путя, рф, короткие, по-русски, национальный,
          сократить, соркащатель, сокращаем, линк, ссылка, ссылки, ссылок,
          ссылочка, клик, твиттер, фейсбук, вконтакте, живой, журнал">
    <meta name="copyright" content="WinkMe, Copyright 2010 - winkme@ctoh.net">
    <meta name="Address" content="Moscow, Saint-Petersburg, Russia" >
    <meta name="Author" content="WinkMe, winkme@ctoh.net">
    <meta name="Design" content="Kripta, kripta@ctoh.net">
    <meta HTTP-EQUIV="Expires" content="Mon, 11 Jun 1998 00:00:01 GMT">
    <meta name="revisit-after" content="10 days">
    <!-- <meta HTTP-EQUIV="pragma" content="no-cache"> -->
    <meta HTTP-EQUIV="Page-Enter" content="BlendTrans(Duration=2.0)">
    <meta HTTP-EQUIV="Page-Exit" content="BlendTrans(Duration=2.0)">

    <link href="css/960.css" rel="stylesheet" type="text/css" />
    <link href="style.css" rel="stylesheet" type="text/css" />

    <!--[if lt IE 9]>
    	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"
                type="text/javascript"></script>
    <![endif]-->

    <!--[if lte IE 7]>
    	<link href="css/ie.css" rel="stylesheet" type="text/css" />
    <![endif]-->

    <script src="http://vkontakte.ru/js/common.js"></script>
    <script src="openapi/openapi_sample.js"></script>

    <script type="text/javascript"
            src="zeroclipboard/ZeroClipboard.js"></script>

    <script language="JavaScript">
            var clip = null;

            function init() {
                clip = new ZeroClipboard.Client();
                clip.setHandCursor( true );

                clip.glue( 'd_clip_button', 'd_clip_container' );

                clip.addEventListener( 'mouseDown', function(client) {
                    // set text to copy here
                    clip.setText( document.getElementById('txtshort').value );

                } );
            }
    </script>
    <script language="JavaScript" type="Text/Javascript">
        <!-- // Hide script from older browsers
        var urlAddress = "<?php echo domain ?>?getlink='+escape(location.href)";
        var pageName = "Сократить с Путя.РФ!";
        function addToFavorites() {
            if (window.external) {
                window.external.AddFavorite(urlAddress,pageName);
            }
            else {
                alert("Sorry! Your browser doesn't support this function.");
            }
        }
        // --></script>
<?php $xajax->printJavascript("xajax/");?>
</head>

<body id="" onLoad="init()">
<?php
/*
    if ( $_SERVER['REMOTE_ADDR'] != '213.170.92.14'){
        echo "<font size='25'>Люди, сайт еще не готов :) откуда вас столько</font>";
        exit;
    }
 */
?>
<!--
    <div id="fb-root"></div>

    <script src="http://connect.facebook.net/en_US/all.js"></script>
    <script>
      FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});
      FB.Event.subscribe('auth.sessionChange', function(response) {
        if (response.session) {
          // A user has logged in, and a new cookie has been saved
        } else {
          // The user has logged out, and the cookie has been cleared
        }
      });
    </script>

    <div id="vk_api_transport"></div>

    <script type="text/javascript" src="openapi/vkAsyncInit.js"></script>

        <div id="openapi_login_wrap" style="margin-left: 30px; margin-right: 15px; width: 150px; float: left">
          <div id="vk_login" onclick="doLogin();"></div>
        </div>
        <div  style="width: 150px; float: left">
            <fb:login-button></fb:login-button>
        </div>
-->
    <div id="divheader">

    </div>

    <div id="divcontent">
        <div id="div-left-side-panel">
            <div id="divlink">

                <input type   ="text"
                       id     ="txtlink"
                       value  ="<?php
                           if ( !isset($_GET['getlink']) )
                               { echo empty_link_text; }
                           else { echo $_GET['getlink']; } ?>"
                       onclick="if (this.value=='<?php echo empty_link_text ?>')
                                    { this.value='' }"
                       onblur ="if (this.value=='')
                                    { this.value='<?php echo empty_link_text ?>' }"
                       onkeyup="if (event.keyCode == 13) {
                                    xajax_get_short_link(this.value)
                                }"
                />

            </div>
            <div id="divshort">

                <input type="text" id="txtshort" readonly
                       value="<?php echo $free_url ?>" />

<?php if (!strpos($_SERVER['HTTP_USER_AGENT'],"MSIE")) { ?>

                <div id="d_clip_container">
                    <div id="d_clip_button" class="my_clip_button">Копируем</div>
                </div>

<?php } ?>

            </div>
        </div>

        <div id="divbutton">

            <button id="btngetshort"
                    onclick="xajax_get_short_link(document.getElementById('txtlink').value)"
            />

        </div>
    </div>

    <div id="divfooter">
        <p id="copyright">&copy; 2011 ПУТЯ.РФ</p>
    </div>

    <div id="dropbookmarks">
        <a href="javascript:location.href='<?php echo domain ?>?getlink='+escape(location.href)"
           onclick="javascript:addToFavorites()">
            Сократить с Путя.РФ!
        </a><b> - тащи в закладки</b>
        &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
        &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    </div>

<?php if (!isset($_SESSION['authorized'])) { ?>

    <script src="http://loginza.ru/js/widget.js" type="text/javascript"></script>
    <a href="https://loginza.ru/api/widget?token_url=http://путя.рф/Loginza.php" id="loginza">Войти через OpenID</a>

<?php }
else {
        echo $_SESSION['authorized']." ".$_SESSION['identity']." ".$_SESSION['provider']." ".$_SESSION['photo']." ".$_SESSION['first_name']." ".$_SESSION['last_name']." ".$_REQUEST[session_name()];
}

?>

<!-- Yandex.Metrika counter -->
<div style="display:none;"><script type="text/javascript">
(function(w, c) {
    (w[c] = w[c] || []).push(function() {
        try {
            w.yaCounter3294052 = new Ya.Metrika(3294052);
             yaCounter3294052.clickmap(true);

        } catch(e) {}
    });
})(window, 'yandex_metrika_callbacks');
</script></div>
<script src="//mc.yandex.ru/metrika/watch.js" type="text/javascript" defer="defer"></script>
<noscript><div style="position:absolute"><img src="//mc.yandex.ru/watch/3294052" alt="" /></div></noscript>
<!-- /Yandex.Metrika counter -->

</body>
</html>